var api = require("../../../utils/mr_xu/api_url.js").api
var request = require("../../../utils/mr_xu/request.js")
var common = require("../../../utils/mr_xu/common.js")
var config = require("../../../utils/mr_xu/config.js")
var orderCache = require("../../../utils/mr_xu/apply_order_cache.js")
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cancel_fee: 1000,
    free_cancel_limit_time: '',
    item: null,
    load: false,
    businessConfig: {
      1: "将车送到指定地点",
      2: "仅找车",
      3: "找车且送到自定地点"
    },
    statusConfig: common.statusConfig,
    toIndexTag: true, //是否一定展示去首页按钮，目前是新建订单的时候设为1
    id: '',
    limit_pay_time: '',
    config_distance_limit: 0, //距离超过这个数，才能补差
    config_time_limit: '', //补差的限时
    showTime: '',
    showLimit:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    let toIndex = options.toIndex ? true : false
    console.log(options.toIndex)
    console.log(toIndex)
    let id = options.id
    id = id ? id : 'e3e9f3f8bb544a4398435cbf8450d513'
    this.setData({
      id: id
    })
    this.setData({
      toIndexTag: toIndex
    })
    this.setConfig()
    this.initGetData(id)

  },
  setShowTime() {
    let showTime = this.data.showTime
    let item = this.data.item

    if (item.carriedTime)
      showTime = item.carriedTime
    else if (item.differenceTime)
      showTime = item.differenceTime
    else if (item.buckleTime)
      showTime = item.buckleTime
    else if (item.findTime)
      showTime = item.findTime
    else
      showTime = item.createTime

    this.setData({
      showTime: showTime
    })
  },
  setConfig() {
    let settings = wx.getStorageSync('settings')
    for (let i in settings) {
      if (settings[i].key == 'QUEST_DIFERENCE_DISTANCE') {
        this.setData({
          config_distance_limit: settings[i].value
        })
      }
      if (settings[i].key == 'QUEST_DIFFERENCE_TIME') {
        this.setData({
          config_time_limit: settings[i].value
        })
      }
    }
  },
  initGetData(id) {
    let that = this
    request.post(api.apply_order_detail_payed, {
      data: id
    }, function(res) {
      let showLimit = res.obj.limitTime &&  common.strtotime(res.obj.limitTime) > (new Date()).getTime() / 1000 ? true : false
      that.setData({
        item: res.obj,
        load: true,
        showLimit: showLimit
      })

      that.setShowTime()

    })
    this.initConfig()
  },
  initConfig() {
    let that = this
    request.post(api.system_config, {
      "data": ""
    }, function(res) {
      let items = res.obj
      for (let i in items) {
        if (items[i].key == "QUEST_REVOKE_MONEY") {
          that.setData({
            cancel_fee: parseInt(items[i].value)
          })
        }
        if (items[i].key == "QUEST_LIMIT_MIN_TIME") {
          that.setData({
            free_cancel_limit_time: parseInt(items[i].value)
          })
        }
        if (items[i].key == "QUEST_PAY_TIME") {
          that.setData({
            limit_pay_time: parseInt(items[i].value)
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  toIndex() {
    wx.reLaunch({
      url: config.INDEX_PAGE,
    })
  },

  edit() {

    if (this.data.item && typeof this.data.item == 'object') {
      orderCache.setUpdateInfo(this.data.item)
      wx.reLaunch({
        url: '/pages/user_side/step1_select_car_status/select_car_status?do=update',
      })
    } else {
      wx.showToast({
        title: '订单数据错误',
      })
    }

  },
  cancel() {

    let that = this
    var oldTime = common.strtotime(that.data.item.createTime)
    var now = (new Date()).valueOf() / 1000;
    var diff = (now - oldTime) / 86400

    if (diff < that.data.free_cancel_limit_time) {
      wx.showModal({
        title: '订单未满' + that.data.free_cancel_limit_time + '天',
        content: '需要扣除手续费' + that.data.cancel_fee + '元',
        confirmText: "支付",
        cancelText: "不撤销",
        success: function(res) {
          if (res.confirm) {
            that.doCancel()
          }
        }
      })
      return
    }

    that.doCancel()
  },
  doCancel() {
    let that = this
    request.post(api.cancel_quest_order, {
      data: that.data.item.id
    }, function(res) {
      if (res.code == 200) {
        wx.showToast({
          title: res.msg,
          success: function() {
            wx.reLaunch({
              url: config.INDEX_PAGE,
            })
          }
        })
      }
    })
  },
  preview(e) {
    let image = e.target.dataset.image
    if (image) {
      wx.previewImage({
        urls: [image],
      })
    }
  },
  toPay() {
    let that = this
    app.http.post(api.quest_order_pay, {
        data: that.data.id
      })
      .then(res => {
        wx.showToast({
          title: '支付成功',
          icon: 'null'
        })
        that.initGetData(that.data.id)
      })

  },
  refuse() {
    let that = this
    wx.showModal({
      title: '确认',
      content: '请确认这不是您的车？',
      confirmText: "确定",
      cancelText: "不撤销",
      success: function (res) {
        if (res.confirm) {
          app.http.post(api.refuse_car, {
            data: that.data.item.id
          })
            .then(res => {
              wx.showToast({
                title: res.msg,
              })
              that.initGetData(that.data.id)
            })
        }
      }
    })
    
  },
  toMobile(e) {
    let mobile = e.currentTarget.dataset.mobile
    wx.makePhoneCall({
      phoneNumber: mobile,
    })
  },
  look_in_map(e) {
    let coords = e.target.dataset.coords

    if (!coords) {
      coords = e.currentTarget.dataset.coords
    }

    let latitude = coords.split(',')[1]
    let longitude = coords.split(',')[0]

    wx.openLocation({
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
    })
  },
  confirmSend() {
    let that = this
    app.http.post(api.confirm_send_car, {
        data: this.data.item.id
      })
      .then(res => {
        wx.showToast({
          title: res.msg,
        })
        that.initGetData(that.data.id)
      })

  },
  toKefu() {
    wx.showToast({
      title: '即将开放',
      icon: 'null'
    })
  },
  payDifference() {
    let that = this
    app.http.post(api.user_agree_more_money, {
        data: that.data.item.id
      })
      .then(res => {
        wx.showToast({
          title: res.msg,
          icon: 'null'
        })
        that.initGetData(that.data.id)
      })
  },
  resetAddr() {
    let that = this
    wx.chooseLocation({
      success: function(res) {

        if (res.errMsg == 'chooseLocation:ok') {
          let coords = res.longitude + ',' + res.latitude
          let address = res.address
          app.http.post(api.apply_more_money_advise, {
            data: {
              locationCoords: that.data.item.locationCoords,
              destinationCoords: coords
            }
          }).then(res => {
            if (res.obj <= 0) {
            
              app.http.post(api.change_destination, {
                data: {
                  id: that.data.id,
                  revise: address,
                  reviseCoords: coords
                }
              }).then(res => {
                that.initGetData(that.data.id)
              })

            } else {
              wx.showToast({
                title: '改动距离过大',
                icon: 'none'
              })
            }

          })

          return

          
        }
      },
    })

  }
})